package com.seeyon.kk.utils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;

import com.seeyon.apps.kk.manager.BaseManager;
import com.seeyon.ctp.common.AppContext;

public class LdapUtils extends BaseManager {
	private static final Log Log = LogFactory.getLog(LdapUtils.class);
	private final static String ldapurl = AppContext.getSystemProperty("kk.ad.ldapurl");// LDAP访问地址
	private final static String adminname = AppContext.getSystemProperty("kk.ad.adminname");// AD域用户名
	private final static String adminpassword = AppContext.getSystemProperty("kk.ad.adminpassword");// AD域密码
	private final static String searchbase = AppContext.getSystemProperty("kk.ad.searchbase");// AD根目录地址
	private static LdapContext ctx = null;
	private final static String searchFilter = "objectClass=organizationalUnit"; // 查询组织单位
	private static Map<String, String> defaultMap = new HashMap<String, String>();

	static {
		defaultMap.put("disAccount", "禁用人员");
		defaultMap.put("otherAccount", "其他人员");
	}

	private Map<String, String> msgMap = new HashMap<>();

	/**
	 * 添加组织部门
	 * 
	 * @param vl2
	 * @return true or false
	 */
	public boolean addAdDept(List<Map<String, Object>> vl) {
		if (vl.isEmpty())
			return false;

		BasicAttributes attrsbu = null;
		BasicAttribute objclassSet = null;
		Map<String, String> pathMap = new HashMap<>();
		Map<String, String> deptMap = new HashMap<>();
		try {
			ctx = init(); // 连接ad初始化
			NamingEnumeration answer = ctx.search("OU=" + vl.get(0).get("name").toString() + "," + searchbase,
					searchFilter, setAttribute());
			if (answer != null) {
				while (answer.hasMoreElements()) {
					SearchResult sr = (SearchResult) answer.next();
					Attributes Attrs = sr.getAttributes();
					if (Attrs != null) {
						String code = Attrs.get("description") == null ? null
								: Attrs.get("description").get().toString();// 获取部门编号
						if (code != null) {
							deptMap.put(code, code);
						}
					}
				}
			}
		} catch (NamingException e) {
			Log.error("LDAP addAdDept is init Error!");
			return false;
		}

		String companypath = "ou=" + vl.get(0).get("name").toString() + ",";
		for (Map<String, Object> map : vl) {
			attrsbu = new BasicAttributes();
			objclassSet = new BasicAttribute("objectclass");
			objclassSet.add("top");
			objclassSet.add("organizationalUnit");
			attrsbu.put(objclassSet);
			String ou = "";
			pathMap.put(MapUtils.getString(map, "path"), MapUtils.getString(map, "name"));
			String path = MapUtils.getString(map, "path");
			String tempcode = MapUtils.getString(map, "code");
			// 验证部门是否存在
			if (!StringUtils.equals(tempcode, MapUtils.getString(deptMap, tempcode))) {
				attrsbu.put("ou", MapUtils.getString(map, "name").replaceAll("/", "-"));
				attrsbu.put("description", tempcode);
				for (int i = 1; i <= path.length() / 4 - 1; i++) {
					if (i == 1)
						ou += "ou=" + pathMap.get(path).replaceAll("/", "-") + ",";
					else
						ou += "ou=" + pathMap.get(path.substring(0, path.length() - 4 * (i - 1))).replaceAll("/", "-")
								+ ",";
				}
				ou += searchbase;
				try {
					ctx.createSubcontext(ou, attrsbu);
					/**
					 * 创建通讯组
					 */
					attrsbu = new BasicAttributes();
					objclassSet = new BasicAttribute("objectclass");
					objclassSet.add("top");
					objclassSet.add("group");
					attrsbu.put(objclassSet);
					attrsbu.put("cn", MapUtils.getString(map, "name").replaceAll("/", "-"));
					attrsbu.put("sAMAccountName", tempcode);
					attrsbu.put("name", MapUtils.getString(map, "name"));
					attrsbu.put("mail", tempcode + "@locknlock.com.cn");
					attrsbu.put("groupType", "8");
					String groupPath = "cn=" + MapUtils.getString(map, "name").replaceAll("/", "-") + "," + ou;
					ctx.createSubcontext(groupPath, attrsbu); // 上级

					if (path.length() / 4 - 1 != 1) {
						String strs = ou.substring(ou.indexOf(",") + 1, ou.length());
						String str = "CN="
								+ MapUtils.getString(pathMap, path.substring(0, path.length() - 4)).replaceAll("/", "-")
								+ "," + strs;
						ModificationItem[] mods = new ModificationItem[1];
						Attribute sn = new BasicAttribute("member", groupPath);
						mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, sn);
						ctx.modifyAttributes(str, mods); // 拼接之后的上级通讯组
					}
				} catch (NamingException e) {
					Log.error(
							"LDAP is addAdDept is error :url=" + ou + "; deptName=" + MapUtils.getString(map, "name"));
					continue;
				}
			}
		}
		try {
			String disNamenFlag = MapUtils.getString(deptMap, "disAccount");
			String noDeptName = MapUtils.getString(deptMap, "otherAccount");
			if (StringUtils.equals(disNamenFlag, null)) {
				attrsbu = new BasicAttributes();
				objclassSet = new BasicAttribute("objectclass");
				objclassSet.add("top");
				objclassSet.add("organizationalUnit");
				attrsbu.put(objclassSet);
				attrsbu.put("ou", MapUtils.getString(defaultMap, "disAccount"));
				attrsbu.put("description", "disAccount");

				ctx.createSubcontext(
						"ou=" + MapUtils.getString(defaultMap, "disAccount") + "," + companypath + searchbase, attrsbu);

				attrsbu = new BasicAttributes();
				objclassSet = new BasicAttribute("objectclass");
				objclassSet.add("top");
				objclassSet.add("group");
				attrsbu.put(objclassSet);
				attrsbu.put("cn", MapUtils.getString(defaultMap, "disAccount"));
				attrsbu.put("sAMAccountName", "disAccount@locknlock.com.cn");
				attrsbu.put("name", MapUtils.getString(defaultMap, "disAccount"));
				attrsbu.put("displayName", "disAccount@locknlock.com.cn");
				attrsbu.put("groupType", "8");
				ctx.createSubcontext(
						"cn=" + MapUtils.getString(defaultMap, "disAccount") + ",ou="
								+ MapUtils.getString(defaultMap, "disAccount") + "," + companypath + searchbase,
						attrsbu);
			}
			if (StringUtils.equals(noDeptName, null)) {
				attrsbu = new BasicAttributes();
				objclassSet = new BasicAttribute("objectclass");
				objclassSet.add("top");
				objclassSet.add("organizationalUnit");
				attrsbu.put(objclassSet);
				attrsbu.put("ou", MapUtils.getString(defaultMap, "otherAccount"));
				attrsbu.put("description", "otherAccount");

				ctx.createSubcontext(
						"ou=" + MapUtils.getString(defaultMap, "otherAccount") + "," + companypath + searchbase,
						attrsbu);

				attrsbu = new BasicAttributes();
				objclassSet = new BasicAttribute("objectclass");
				objclassSet.add("top");
				objclassSet.add("group");
				attrsbu.put(objclassSet);
				attrsbu.put("cn", MapUtils.getString(defaultMap, "otherAccount"));
				attrsbu.put("sAMAccountName", "otherAccount@locknlock.com.cn");
				attrsbu.put("name", MapUtils.getString(defaultMap, "otherAccount"));
				attrsbu.put("displayName", "otherAccount@locknlock.com.cn");
				attrsbu.put("groupType", "8");
				ctx.createSubcontext(
						"cn=" + MapUtils.getString(defaultMap, "otherAccount") + ",ou="
								+ MapUtils.getString(defaultMap, "otherAccount") + "," + companypath + searchbase,
						attrsbu);
				ModificationItem[] mods = new ModificationItem[1];
				Attribute sn = new BasicAttribute("member", "cn=" + MapUtils.getString(defaultMap, "otherAccount")
						+ ",ou=" + MapUtils.getString(defaultMap, "otherAccount") + "," + companypath + searchbase);
				mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, sn);
				ctx.modifyAttributes("cn=" + vl.get(0).get("name").toString() + "," + companypath + searchbase, mods);
			}
		} catch (NamingException e) {
			Log.error("LDAP addAdDept is Other error!");
			return false;
		}
		close();
		return true;
	}

	/**
	 * 修改组织单位
	 * 
	 * @param vl
	 *            组织架构列表
	 * @return
	 */
	public boolean updateAdDept(List<Map<String, Object>> vl) {
		if (vl.isEmpty())
			return false;

		Map<String, String> dept = new HashMap<>(); // 暂存部门path 、name
		Map<String, Map<String, String>> pathMap = getADDept(vl.get(0).get("name").toString());
		/**
		 * 第一步：先获取没改变的部门条目 and code 第二步：验证code 进行数据迁移 rename() 第三步：验证是否修改部门名称
		 */
		ctx = init(); // 连接ad初始化
		for (Map<String, Object> map : vl) {
			String newOu = "";
			String code = MapUtils.getString(map, "code");
			String deptName = MapUtils.getString(map, "name");
			String adCode = MapUtils.getString(MapUtils.getMap(pathMap, code), "code");
			String adPath = MapUtils.getString(MapUtils.getMap(pathMap, code), "pathName");
			String adName = MapUtils.getString(MapUtils.getMap(pathMap, code), "name");
			dept.put(MapUtils.getString(map, "path"), MapUtils.getString(map, "name"));
			String path = MapUtils.getString(map, "path");
			if (StringUtils.equals(code, adCode)) {
				// 先拼接新条目
				for (int i = 1; i <= path.length() / 4 - 1; i++) {
					if (i == 1)
						newOu += "OU=" + dept.get(path).replaceAll("/", "-") + ",";
					else
						newOu += "OU=" + dept.get(path.substring(0, path.length() - 4 * (i - 1))).replaceAll("/", "-")
								+ ",";
				}
				newOu += searchbase;

				/**
				 * 防止修改通讯组出错
				 */

				String groupNameInNamespace = "";
				/*
				 * NamingEnumeration answer = ctx.search(newOu,
				 * "objectClass=group", setAttribute()); String member = ""; //
				 * 通讯组成员 if (answer != null) { while (answer.hasMoreElements())
				 * { SearchResult sr = (SearchResult) answer.next(); Attributes
				 * Attrs = sr.getAttributes(); groupNameInNamespace =
				 * sr.getNameInNamespace(); if (Attrs != null) { member =
				 * Attrs.get("member") == null ? null :
				 * Attrs.get("member").toString(); if (groupNameInNamespace
				 * .substring(groupNameInNamespace.indexOf(",") + 1,
				 * groupNameInNamespace.length()) .equals(newOu)) break; } } }
				 */
				// 与AD 条目进行验证 ctx.renam
				if (!StringUtils.equals(newOu, adPath)) {
					try {
						if (StringUtils.equals(deptName.replaceAll("/", "-"), adName)) {
							if (path.length() / 4 - 1 != 1) {
								String strs = newOu.substring(newOu.indexOf(",") + 1, newOu.length());
								String str = "CN=" + MapUtils.getString(pathMap, path.substring(0, path.length() - 4))
										.replaceAll("/", "-") + "," + strs;
								ModificationItem[] mods = new ModificationItem[1];
								Attribute sn = new BasicAttribute("member", groupNameInNamespace);
								mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, sn);
								ctx.modifyAttributes(str, mods); // 拼接之后的上级通讯组

								String[] tempstr = groupNameInNamespace.split(",");
								String parentName = tempstr[2].substring(tempstr[2].indexOf("=") + 1,
										tempstr[2].length());
								String parentGroupPath = "cn=" + parentName + ",";
								for (int i = 2; i < tempstr.length; i++) {
									if (i < tempstr.length - 1)
										path += tempstr[i] + ",";
									else
										path += tempstr[i];
								}
								sn = new BasicAttribute("member", groupNameInNamespace);
								mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, sn);
								ctx.modifyAttributes(parentGroupPath, mods); // 从父级通讯组移除
							}
							ctx.rename(groupNameInNamespace, "cn=" + deptName.replaceAll("/", "-") + "," + adPath);
						}
						Log.info("=========shkk ldap loadOu:" + adPath + "\n newOu" + newOu);
						ctx.rename(adPath, newOu); // 条目迁移
					} catch (NamingException e) {
						Log.error("LDAP updateDept is error: loadUrl=" + adPath + "; newUrl=" + newOu);
					}
				}
			}
		}
		close(); // 关闭连接
		return true;
	}

	/**
	 * 创建AD安全组
	 * 
	 * @param group
	 *            安全组名称
	 * @return
	 */
	public boolean addGroup(List<Map<String, Object>> vl, String group) {
		try {
			ctx = init();
			String temp = "OU=" + group;
			boolean tempFlag = false;
			NamingEnumeration answer = ctx.search(searchbase, "objectClass=group", setAttribute());
			String groupNameInNamespace = "";
			if (answer != null) {
				while (answer.hasMoreElements()) {
					SearchResult sr = (SearchResult) answer.next();
					String name = sr.getName();
					if (name.equals("(GROUP)_LOCKNLOCK_CHINA")) {
						groupNameInNamespace = sr.getNameInNamespace();
						tempFlag = true;
						break;
					}
				}
			}
			if (tempFlag) {
				String tempGroup = groupNameInNamespace.substring(groupNameInNamespace.indexOf(",") + 1,
						groupNameInNamespace.length());
				String tempOu = temp + "," + searchbase;
				if (!StringUtils.equals(tempGroup, tempOu))
					ctx.rename(tempGroup, tempOu);
			} else {
				// 先验证组织单位是否存在
				answer = ctx.search(searchbase, searchFilter, setAttribute());
				boolean flag = false; // 标记组ou是否存在,
				if (answer != null) {
					while (answer.hasMoreElements()) {
						SearchResult sr = (SearchResult) answer.next();
						String name = sr.getName();
						if (name.equals(temp)) {
							flag = true;
							break;
						}
					}
				}
				if (!flag) {
					BasicAttributes attrsbu = new BasicAttributes();
					BasicAttribute objclassSet = new BasicAttribute("objectclass");
					objclassSet.add("top");
					objclassSet.add("organizationalUnit");
					attrsbu.put(objclassSet);
					attrsbu.put("ou", group);
					ctx.createSubcontext(temp + "," + searchbase, attrsbu);
					attrsbu = new BasicAttributes();
					objclassSet = new BasicAttribute("objectclass");
					objclassSet.add("top");
					objclassSet.add("group");
					attrsbu.put(objclassSet);
					attrsbu.put("cn", "(GROUP)_LOCKNLOCK_CHINA");
					attrsbu.put("sAMAccountName", "(GROUP)_LOCKNLOCK_CHINA");
					attrsbu.put("name", "(GROUP)_LOCKNLOCK_CHINA");
					ctx.createSubcontext("cn=(GROUP)_LOCKNLOCK_CHINA," + temp + "," + searchbase, attrsbu);
				}
				Map<String, Map<String, String>> groupMap = new HashMap<>();
				answer = ctx.search(searchbase, "objectClass=group", setAttribute());
				if (answer != null) {
					while (answer.hasMoreElements()) {
						SearchResult sr = (SearchResult) answer.next();
						Attributes Attrs = sr.getAttributes();
						if (Attrs != null) {
							Map<String, String> map = new HashMap<>();
							String groupCode = Attrs.get("name") == null ? null : Attrs.get("name").get().toString();
							groupCode = groupCode.substring(groupCode.indexOf("_") + 1, groupCode.length());
							map.put("path", sr.getNameInNamespace());
							map.put("code", groupCode);
							groupMap.put(groupCode, map);
						}
					}
				}
				BasicAttributes attrsbu = new BasicAttributes();
				BasicAttribute objclassSet = new BasicAttribute("objectclass");
				objclassSet.add("top");
				objclassSet.add("group");
				attrsbu.put(objclassSet);
				for (Map<String, Object> map : vl) {
					String code = MapUtils.getString(map, "company");
					String adCode = MapUtils.getString(MapUtils.getMap(groupMap, code), "code");
					if (!StringUtils.equals(code, adCode)) {
						attrsbu.put("cn", "(GROUP)_" + code);
						attrsbu.put("sAMAccountName", "(GROUP)_" + code);
						attrsbu.put("name", "(GROUP)_" + code);
						ctx.createSubcontext("cn=(GROUP)_" + code + "," + temp + "," + searchbase, attrsbu);
						ModificationItem[] mods = new ModificationItem[1];
						Attribute sn = new BasicAttribute("member",
								"cn=(GROUP)_" + code + "," + temp + "," + searchbase);
						mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, sn);
						ctx.modifyAttributes("cn=(GROUP)_LOCKNLOCK_CHINA," + temp + "," + searchbase, mods);
					}
				}
			}
			return true;
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			Log.error("LadpUtils addGroup error:", e);
			Log.error("LadpUtils addGroup 安全组创建错误！:", e);
		}
		return false;
	}

	/**
	 * 获取ad全部组织单位
	 * 
	 * @param companyName
	 * @return
	 */
	private static Map<String, Map<String, String>> getADDept(String companyName) {
		Map<String, Map<String, String>> pathMap = new HashMap<>(); // 获取ad全部组织单位
		try {
			NamingEnumeration answer = getADInfoAll(companyName);
			if (answer != null) {
				while (answer.hasMoreElements()) {
					SearchResult sr = (SearchResult) answer.next();
					Attributes Attrs = sr.getAttributes();
					if (Attrs != null) {
						String sAMAccountName = Attrs.get("sAMAccountName") == null ? null
								: Attrs.get("sAMAccountName").get().toString();// 登录名也是工号
						// 只查询部门信息过滤人员
						if (sAMAccountName == null) {
							Map<String, String> deptMap = new HashMap<>();
							String pathName = sr.getNameInNamespace(); // 部门所在条目
							String name = Attrs.get("name") == null ? null : Attrs.get("name").get().toString();// 人员姓名
							String code = Attrs.get("description") == null ? null
									: Attrs.get("description").get().toString();// 获取部门编号
							deptMap.put("code", code);
							deptMap.put("pathName", pathName);
							deptMap.put("name", name);
							pathMap.put(code, deptMap);
						}
					}
				}
			}
			return pathMap;
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			Log.error("LadpUtils getADDept error:", e);
			Log.error("LadpUtils getADDept AD部门数据获取错误！:", e);
		}
		return null;
	}

	/**
	 * 
	 * @param objMap
	 *            需要添加的人员map
	 * @param companyName
	 *            组织单位名称, group安全组ou名称
	 * @return 添加用户
	 */
	@SuppressWarnings("unused")
	public Map<String, String> addMember(List<Map<String, Object>> vl, String companyName, String group) {
		if (vl.isEmpty()) {
			msgMap.put("code", "1000");
			msgMap.put("message", "");
			return msgMap;
		}

		ctx = init(); // 建立ad连接
		NamingEnumeration answer = null;
		Map<String, Map<String, String>> map = null;
		Map<String, Map<String, String>> memberMap = null;
		try {
			answer = ctx.search("OU=" + companyName + "," + searchbase, "objectClass=user", setAttribute());
			map = new HashMap<>();
			memberMap = new HashMap<>();
			if (answer != null) {
				while (answer.hasMoreElements()) {
					SearchResult sr = (SearchResult) answer.next();
					Attributes Attrs = sr.getAttributes();
					if (Attrs != null) {
						Map<String, String> temp = new HashMap<>();
						String memberCode = Attrs.get("employeeID") == null ? null
								: Attrs.get("employeeID").get().toString();
						String sAMAccountName = Attrs.get("sAMAccountName") == null ? null
								: Attrs.get("sAMAccountName").get().toString();// 人员编号
						String userPrincipalName = Attrs.get("userPrincipalName") == null ? null
								: Attrs.get("userPrincipalName").get().toString();
						if (sAMAccountName != null) {
							temp.put("code", memberCode);
							temp.put("login", sAMAccountName.toLowerCase());
							temp.put("emailLogin", userPrincipalName);
							temp.put("path", sr.getNameInNamespace());
							if (userPrincipalName == null) {
								memberMap.put(sAMAccountName.toLowerCase(), temp);
							} else {
								userPrincipalName = userPrincipalName.substring(0, userPrincipalName.indexOf("@"));
								memberMap.put(userPrincipalName.toLowerCase(), temp);
							}
						}
					}
				}
			}
			// 获取AD部门条目
			answer = ctx.search("OU=" + companyName + "," + searchbase, searchFilter, setAttribute());
			if (answer != null) {
				while (answer.hasMoreElements()) {
					SearchResult sr = (SearchResult) answer.next();
					Attributes Attrs = sr.getAttributes();
					if (Attrs != null) {
						Map<String, String> temp = new HashMap<>();
						String description = Attrs.get("description") == null ? null
								: Attrs.get("description").get().toString();// 获取部门编号
						if (description != null) {
							temp.put(description, sr.getNameInNamespace());
							map.put(description, temp);
						}
					}
				}
			}
		} catch (NamingException e) {
			Log.info("kk LDAP AddMember 连接  error!");
			msgMap.put("code", "1001");
			msgMap.put("message", "kk LDAP AddMember 连接  error!");
			close(); // 关闭连接
			return msgMap;
		}
		for (Map<String, Object> objMap : vl) {
			if (MapUtils.getInteger(objMap, "is_enable") == 0)
				continue;
			String memberCode = MapUtils.getString(objMap, "uCode");
			String tempDept = MapUtils.getString(objMap, "dCode"); // 获取人员所在的部门编号
			String uName = MapUtils.getString(objMap, "uName");
			String tempPath = MapUtils.getString(MapUtils.getMap(map, tempDept), tempDept); // 获取部门在AD的条目录
			String tempname = uName + "[" + MapUtils.getString(objMap, "login_name") + "]";
			String telephone = MapUtils.getString(objMap, "telephone"); // 电话
			String phone = MapUtils.getString(objMap, "phone");
			String password = MapUtils.getString(objMap, "password"); // 密码
			String userOrEmail = MapUtils.getString(objMap, "email");
			String title = MapUtils.getString(objMap, "title"); // 职务
			String department = MapUtils.getString(objMap, "dname"); // 部门
			String company = MapUtils.getString(objMap, "company"); // 地区
			String country = MapUtils.getString(objMap, "country"); // 国家
			String login = MapUtils.getString(objMap, "login_name") == null ? null
					: MapUtils.getString(objMap, "login_name");
			if (login == null)
				continue;
			String adcode = MapUtils.getString(MapUtils.getMap(memberMap, login.toLowerCase()), "code");
			String adlogin = MapUtils.getString(MapUtils.getMap(memberMap, login.toLowerCase()), "login") == null ? null
					: MapUtils.getString(MapUtils.getMap(memberMap, login.toLowerCase()), "login");
			String adEmailLogin = MapUtils.getString(MapUtils.getMap(memberMap, login.toLowerCase().replace(" ", "")),
					"emailLogin") == null ? null
							: MapUtils.getString(MapUtils.getMap(memberMap, login.toLowerCase().replace(" ", "")),
									"emailLogin");
			String adPath = MapUtils.getString(MapUtils.getMap(memberMap, login.toLowerCase().replace(" ", "")),
					"path");
			if (adEmailLogin != null)
				adEmailLogin = adEmailLogin.substring(0, adEmailLogin.indexOf("@"));
			if (login.equals("xianwu.li"))
				System.out.println("xianwu.li === " + adlogin);
			if (!StringUtils.equals(login.toLowerCase().replace(" ", ""), adlogin)
					&& !StringUtils.equals(login.toLowerCase().replace(" ", ""), adEmailLogin)) {
				// 添加人员信息
				BasicAttributes attrsbu = new BasicAttributes();
				BasicAttribute objclassSet = new BasicAttribute("objectclass");
				objclassSet.add("top");
				objclassSet.add("person");
				objclassSet.add("user");
				objclassSet.add("posixAccount");
				objclassSet.add("shadowAccount");
				try {
					attrsbu.put(objclassSet);
					attrsbu.put("cn", tempname); // 姓名
					String str = uName.substring(0, 1);
					attrsbu.put("sn", str); // 姓
					str = uName.substring(1, uName.length());
					attrsbu.put("givenName", str); // 名
					attrsbu.put("displayName", uName); // 显示名称
					if (company != null)
						attrsbu.put("company", company); // 公司
					attrsbu.put("department", department); // 部门
					attrsbu.put("title", title); // 职务
					if (telephone != null) {
						attrsbu.put("telephoneNumber", telephone); // 电话
					}
					if (userOrEmail != null) {
						attrsbu.put("mail", userOrEmail); // 邮箱
					}
					if (phone != null) {
						attrsbu.put("mobile", phone); // 手机
					}
					if (country != null)
						attrsbu.put("c", country.replaceAll(" ", "")); // 国家
					attrsbu.put("userPrincipalName", MapUtils.getString(objMap, "login_name") + "@locknlock.com.cn"); // 用户名
					attrsbu.put("userPassword", password); // 密码
					attrsbu.put("sAMAccountName", MapUtils.getString(objMap, "login_name"));// 登录名
					/**
					 * 设置用户属性 (用户不能更改密码 ：64，密码永不过期： 66144
					 */
					attrsbu.put("userAccountControl", "66144");
					attrsbu.put("employeeID", MapUtils.getString(objMap, "uCode"));// 人员编号
					attrsbu.put("departmentNumber", tempDept);// 部门编号
					this.ibatisQueryDao.getSqlMapClientTemplate().insert("addTempOrgAD_insert_lockkk", objMap);
					Log.info("======shkk ldap ou:" + "cn=" + tempname + "," + tempPath);
					ctx.createSubcontext("cn=" + tempname + "," + tempPath, attrsbu);
					// 把人员添加安全組 及通訊組
					ModificationItem[] mods = new ModificationItem[1];
					if (company != null) {
						Attribute memberCompany = new BasicAttribute("member", "cn=" + tempname + "," + tempPath);
						mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, memberCompany);
						ctx.modifyAttributes("cn=(GROUP)_" + company + ",OU=" + group + "," + searchbase, mods);
					}
					Attribute memberDept = new BasicAttribute("member", "cn=" + tempname + "," + tempPath);
					mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, memberDept);
					ctx.modifyAttributes("cn=" + department.replaceAll("/", "-") + "," + tempPath, mods);

					String newQuotedPassword = "\"" + password + "\"";
					byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
							new BasicAttribute("unicodePwd", newUnicodePassword));
					ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);
					Log.info("账号添加成功：" + MapUtils.getString(objMap, "login_name"));
				} catch (DataAccessException e) {
					Log.info("kk LDAP AddMember error:attrsbu=[" + attrsbu + "],url:[cn=" + tempname + "," + tempPath
							+ "]");
					Log.info("======shkk ldap ou:" + "cn=" + tempname + "," + tempPath);
					continue;
				} catch (UnsupportedEncodingException e) {
					Log.info("kk LDAP AddMember error:attrsbu=[" + attrsbu + "],url:[cn=" + tempname + "," + tempPath
							+ "]");
					Log.info("======shkk ldap ou:" + "cn=" + tempname + "," + tempPath);
					continue;
				} catch (NamingException e) {
					Log.info("kk LDAP AddMember error:attrsbu=[" + attrsbu + "],url:[cn=" + tempname + "," + tempPath
							+ "]");
					Log.info("======shkk ldap ou:" + "cn=" + tempname + "," + tempPath);
					continue;
				}
			}
		}
		msgMap.put("code", "1000");
		msgMap.put("message", "");
		close(); // 关闭连接
		return msgMap;
	}

	/**
	 * 修改人员
	 * 
	 * @param vl
	 * @param companyName
	 * @return
	 */
	@SuppressWarnings("unused")
	public boolean updateMember(List<Map<String, Object>> vl, String companyName, String group) {
		if (vl.isEmpty())
			return true;

		Map<String, Map<String, String>> map = new HashMap<>();;
		Map<String, String> mpath = new HashMap<>();;
		try {
			ctx = init();
			NamingEnumeration answer = ctx.search("OU=" + companyName + "," + searchbase, "objectClass=user",
					setAttribute());
			if (answer == null || answer.equals(null)) {
				System.out.println("answer is null");
			} else {
				System.out.println("answer not null");
			}
			if (answer != null) {
				while (answer.hasMoreElements()) {
					SearchResult sr = (SearchResult) answer.next();
					Attributes Attrs = sr.getAttributes();
					if (Attrs != null) {
						Map<String, String> temp = new HashMap<>();
						String description = Attrs.get("description") == null ? null
								: Attrs.get("description").get().toString();// 获取部门编号
						String path = sr.getNameInNamespace(); // 部门条目
						String sAMAccountName = Attrs.get("sAMAccountName") == null ? null
								: Attrs.get("sAMAccountName").get().toString();
						if (sAMAccountName != null) {
							mpath.put(sAMAccountName.toLowerCase(), path);
						}
					}
				}
			}

			answer = ctx.search("OU=" + companyName + "," + searchbase, "objectClass=organizationalUnit",
					setAttribute());
			if (answer != null) {
				while (answer.hasMoreElements()) {
					SearchResult sr = (SearchResult) answer.next();
					Attributes Attrs = sr.getAttributes();
					if (Attrs != null) {
						Map<String, String> temp = new HashMap<>();
						String description = Attrs.get("description") == null ? null
								: Attrs.get("description").get().toString();// 获取部门编号
						String path = sr.getNameInNamespace(); // 部门条目
						if (description != null) {
							temp.put(description, path);
							map.put(description, temp);
						}
					}
				}
			}
		} catch (NamingException e) {
			Log.error("LDAP updateMember is init Error!");
			return false;
		}

		for (Map<String, Object> objMap : vl) {
			String memberCode = MapUtils.getString(objMap, "uCode");
			String tempDept = MapUtils.getString(objMap, "dCode"); // 获取人员所在的部门编号
			String uName = MapUtils.getString(objMap, "uName");
			String login = MapUtils.getString(objMap, "login_name") == null ? null
					: MapUtils.getString(objMap, "login_name");
			String tempPath = MapUtils.getString(MapUtils.getMap(map, tempDept), tempDept); // 获取部门在AD的条目录
			int isEnable = MapUtils.getInteger(objMap, "is_enable"); // 账号状态
			String tempname = null;
			String phone = MapUtils.getString(objMap, "phone");
			if (isEnable != 0)
				tempname = uName + "[" + MapUtils.getString(objMap, "login_name").toLowerCase() + "]";
			String telephone = MapUtils.getString(objMap, "telephone"); // 电话
			String password = MapUtils.getString(objMap, "password"); // 密码
			String userOrEmail = MapUtils.getString(objMap, "email");
			String company = MapUtils.getString(objMap, "company"); // 公司
			String title = MapUtils.getString(objMap, "title"); // 职务
			String department = MapUtils.getString(objMap, "dname"); // 职务
			// 修改 人员信息
			ModificationItem[] mods = new ModificationItem[1];
			try {
				boolean flag = false;
				if (login.indexOf("(CN)") != -1)
					flag = true;
				if (isEnable == 0 || flag) {
					String liName = MapUtils.getString(objMap, "email").substring(0,
							MapUtils.getString(objMap, "email").indexOf("@")); // 离职人员账号
					Attribute member = new BasicAttribute("userAccountControl", "514");
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, member);
					Map<String, Object> delete = new HashMap<>();
					delete.put("id", MapUtils.getString(objMap, "id"));
					delete.put("is_enable", MapUtils.getString(objMap, "is_enable"));
					ctx.modifyAttributes("cn=" + uName + "[" + liName + "]" + "," + tempPath, mods);
					String disNamePath = "cn=" + uName + "[" + liName + "]" + ",ou="
							+ MapUtils.getString(defaultMap, "disAccount") + ",ou=" + companyName + "," + searchbase;
					ctx.rename("cn=" + uName + "[" + liName + "]" + "," + tempPath, disNamePath);
					this.ibatisQueryDao.getSqlMapClientTemplate().update("updTempOrgAD_delete_lockkk", delete);
				} else {

					String oldPath = MapUtils.getString(mpath, MapUtils.getString(objMap, "login_name").toLowerCase());
					/*
					 * if (isGroubMember(oldPath)) { Attribute addgroup = new
					 * BasicAttribute("member", oldPath); mods[0] = new
					 * ModificationItem(DirContext.REMOVE_ATTRIBUTE, addgroup);
					 * ctx.modifyAttributes(oldPath, mods); }
					 */
					ctx.rename(MapUtils.getString(mpath, MapUtils.getString(objMap, "login_name").toLowerCase()),
							"cn=" + tempname + "," + tempPath);
					Attribute sn = new BasicAttribute("sn", uName.substring(0, 1));
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sn);
					// 修改姓氏
					ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

					Attribute member = new BasicAttribute("userAccountControl", "66144");
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, member);
					ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

					Attribute givenName = new BasicAttribute("givenName", uName.substring(1, uName.length()));
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, givenName);
					ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

					// 修改显示名称
					if (tempname != null) {
						Attribute uptempname = new BasicAttribute("displayName", uName);
						mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, uptempname);
					} else {
						Attribute uptempname = new BasicAttribute("displayName", null);
						mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, uptempname);
					}
					ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

					Attribute upcompany = new BasicAttribute("company", company);
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, upcompany); // 修改公司
					ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

					Attribute updepartment = new BasicAttribute("department", department);
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, updepartment); // 修改部门
					ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

					Attribute uptitle = new BasicAttribute("title", title);
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, uptitle);
					// 修改职务
					ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods); // 修改电话
					if (telephone != null) {
						Attribute uptelephone = new BasicAttribute("telephoneNumber", telephone);
						mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, uptelephone);
						ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);
					}
					// 修改手机号
					if (phone != null) {
						Attribute mobile = new BasicAttribute("mobile", phone);
						mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mobile);
						ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);
					}
					Attribute mail = new BasicAttribute("mail", userOrEmail);
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mail);
					// 修改邮箱
					ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

					Attribute departmentNumber = new BasicAttribute("departmentNumber", tempDept);
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, departmentNumber);
					// 部门编号
					ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

					// 把人员添加入通訊组
					/*
					 * if (isGroubMember("cn=" + tempname + "," + tempPath)) {
					 * Attribute addgroup = new BasicAttribute("member", "cn=" +
					 * tempname + "," + tempPath); mods[0] = new
					 * ModificationItem(DirContext.ADD_ATTRIBUTE, addgroup);
					 * ctx.modifyAttributes("cn=" + department.replaceAll("/",
					 * "-") + "," + tempPath, mods); }
					 */
					ibatisQueryDao.getSqlMapClientTemplate().update("updTempOrgAD_update_lockkk", objMap);
				}
			} catch (DataAccessException e) {
				Log.error("LDAP updateMember is error:url=[cn=" + tempname + "," + tempPath + "]");
				continue;
			} catch (NamingException e) {
				Log.error("LDAP updateMember is error:url=[cn=" + tempname + "," + tempPath + "]");
				continue;
			}
		}
		close(); // 关闭连接
		return true;
	}

	public boolean updateDisOrOther(List<Map<String, Object>> vl, String companyName) {
		if (vl.isEmpty())
			return true;

		ctx = init();
		String disAccountPath = "OU=" + MapUtils.getString(defaultMap, "disAccount") + ",OU=" + companyName + ","
				+ searchbase;
		String otherAccountPath = "OU=" + MapUtils.getString(defaultMap, "otherAccount") + ",OU=" + companyName + ","
				+ searchbase;
		Map<String, String> mpath = new HashMap<>();
		Map<String, String> deptMap = new HashMap<>();
		try {
			NamingEnumeration answer = ctx.search(disAccountPath, "objectClass=user", setAttribute());
			if (answer != null) {
				while (answer.hasMoreElements()) {
					SearchResult sr = (SearchResult) answer.next();
					Attributes Attrs = sr.getAttributes();
					if (Attrs != null) {
						Map<String, String> temp = new HashMap<>();
						String sAMAccountName = Attrs.get("sAMAccountName") == null ? null
								: Attrs.get("sAMAccountName").get().toString();
						if (sAMAccountName != null) {
							mpath.put(sAMAccountName, sr.getNameInNamespace());
						}
					}
				}
			}
			answer = ctx.search(otherAccountPath, "objectClass=user", setAttribute());
			if (answer != null) {
				while (answer.hasMoreElements()) {
					SearchResult sr = (SearchResult) answer.next();
					Attributes Attrs = sr.getAttributes();
					if (Attrs != null) {
						Map<String, String> temp = new HashMap<>();
						String sAMAccountName = Attrs.get("sAMAccountName") == null ? null
								: Attrs.get("sAMAccountName").get().toString();
						if (sAMAccountName != null) {
							mpath.put(sAMAccountName, sr.getNameInNamespace());
						}
					}
				}
			}

			answer = ctx.search("OU=" + companyName + "," + searchbase, searchFilter, setAttribute());
			if (answer != null) {
				while (answer.hasMoreElements()) {
					SearchResult sr = (SearchResult) answer.next();
					Attributes Attrs = sr.getAttributes();
					if (Attrs != null) {
						String description = Attrs.get("description") == null ? null
								: Attrs.get("description").get().toString();// 获取部门编号
						if (description != null) {
							deptMap.put(description, sr.getNameInNamespace());
						}
					}
				}
			}
		} catch (NamingException e) {
			Log.error("LDAP updateDisOrOther is init error!");
			return false;
		}

		for (Map<String, Object> objMap : vl) {
			String memberCode = MapUtils.getString(objMap, "uCode");
			String tempDept = MapUtils.getString(objMap, "dCode"); // 获取人员所在的部门编号
			String uName = MapUtils.getString(objMap, "uName");
			String login = MapUtils.getString(objMap, "login_name") == null ? null
					: MapUtils.getString(objMap, "login_name");

			String tempPath = MapUtils.getString(deptMap, tempDept); // 获取部门在AD的条目录
			String tempname = uName + "[" + MapUtils.getString(objMap, "login_name") + "]";
			String telephone = MapUtils.getString(objMap, "telephone"); // 电话
			String password = MapUtils.getString(objMap, "password"); // 密码
			String userOrEmail = MapUtils.getString(objMap, "email");
			String company = MapUtils.getString(objMap, "company"); // 公司
			String title = MapUtils.getString(objMap, "title"); // 职务
			String department = MapUtils.getString(objMap, "dname"); // 职务
			int isEnable = MapUtils.getInteger(objMap, "is_enable"); // 账号状态
			String adLogin = MapUtils.getString(mpath, login) == null ? null : MapUtils.getString(mpath, login);
			if (adLogin == null)
				continue;
			try {
				// 修改 人员信息
				this.ibatisQueryDao.getSqlMapClientTemplate().insert("addTempOrgAD_insert_lockkk", objMap);
				ModificationItem[] mods = new ModificationItem[1];
				String oldPath = MapUtils.getString(mpath, MapUtils.getString(objMap, "login_name"));

				ctx.rename(oldPath, "cn=" + tempname + "," + tempPath);
				Attribute sn = new BasicAttribute("sn", uName.substring(0, 1));
				mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sn);
				// 修改姓氏
				ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

				Attribute member = new BasicAttribute("userAccountControl", "66144");
				mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, member);
				ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

				Attribute givenName = new BasicAttribute("givenName", uName.substring(1, uName.length()));
				mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, givenName);
				ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

				// 修改显示名称
				if (tempname != null) {
					Attribute uptempname = new BasicAttribute("displayName", uName);
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, uptempname);
				} else {
					Attribute uptempname = new BasicAttribute("displayName", null);
					mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, uptempname);
				}
				ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

				Attribute upcompany = new BasicAttribute("company", company);
				mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, upcompany); // 修改公司
				ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

				Attribute updepartment = new BasicAttribute("department", department);
				mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, updepartment); // 修改部门
				ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

				Attribute uptitle = new BasicAttribute("title", title);
				mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, uptitle);
				// 修改职务
				ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods); // 修改电话
				if (telephone != null) {
					Attribute uptelephone = new BasicAttribute("telephoneNumber", telephone);
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, uptelephone);
					ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);
				}

				Attribute mail = new BasicAttribute("mail", userOrEmail);
				mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mail);
				// 修改邮箱
				ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

				Attribute departmentNumber = new BasicAttribute("departmentNumber", tempDept);
				mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, departmentNumber);
				// 部门编号
				ctx.modifyAttributes("cn=" + tempname + "," + tempPath, mods);

				// 把人员添加入通訊组
				Attribute addgroup = new BasicAttribute("member", "cn=" + tempname + "," + tempPath);
				mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, addgroup);
				ctx.modifyAttributes("cn=" + department.replaceAll("/", "-") + "," + tempPath, mods);
				ibatisQueryDao.getSqlMapClientTemplate().update("updTempOrgAD_update_lockkk", objMap);
			} catch (DataAccessException e) {
				Log.error("LDAP is updateDisOrOther error:url=[cn=" + tempname + "," + tempPath + "]");
				continue;
			} catch (NamingException e) {
				Log.error("LDAP is updateDisOrOther error:url=[cn=" + tempname + "," + tempPath + "]");
				continue;
			}
		}
		close(); // 关闭连接
		return true;
	}

	/**
	 * ldap连接初始化
	 * 
	 * @return DirContext
	 */
	@SuppressWarnings("unchecked")
	private static LdapContext init() {
		Hashtable HashEnv = new Hashtable();
		String javaHome = System.getProperty("java.home");
		String keystore = javaHome + "/lib/security/cacerts";
		// 导入证书
		System.setProperty("javax.net.ssl.trustStore", keystore);
		HashEnv.put(Context.SECURITY_PROTOCOL, "ssl");// 链接认证服务器
		HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别
		HashEnv.put(Context.SECURITY_PRINCIPAL, adminname); // AD User
		HashEnv.put(Context.SECURITY_CREDENTIALS, adminpassword); // AD Password
		HashEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
		HashEnv.put(Context.PROVIDER_URL, ldapurl);
		try {
			return new InitialLdapContext(HashEnv, null);
		} catch (Exception e) {
			Log.error("Active Directory 连接超时！ 或ssl证书验证错误:" + e.getMessage());
			Log.error("LadpUtils init error:", e);
		}
		return null;
	}

	/**
	 * 
	 * @param companyName
	 *            单位名称
	 * @return 设置属性集
	 */
	@SuppressWarnings({ "rawtypes", "unused" })
	private static SearchControls setAttribute() throws NamingException {
		SearchControls searchCtls = new SearchControls();
		searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		String returnedAtts[] = { "url", "whenChanged", "employeeID", "name", "userPrincipalName",
				"physicalDeliveryOfficeName", "departmentNumber", "telephoneNumber", "homePhone", "mobile",
				"department", "sAMAccountName", "whenChanged", "mail", "description", "userAccountControl",
				"accountExpires", "givenName", "initials", "title", "company", "sn", "uid", "member" }; // 定制返回属性
		searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集
		return searchCtls;
	}

	/**
	 * 关闭ldap连接
	 */
	private static void close() {
		try {
			if (ctx != null)
				ctx.close();
		} catch (NamingException e) {
			Log.error("LadpUtils close() error:" + e.getMessage());
		}
	}

	/**
	 * 查询全部组织 or 全部组织及人员信息
	 * 
	 * @param companyName
	 *            组织单位名称
	 */
	private static NamingEnumeration getADInfoAll(String companyName) {
		try {
			// 先验证组织单位是否存在
			if(null == ctx){
				ctx = init();
			}
			
			NamingEnumeration answer = ctx.search(searchbase, searchFilter, setAttribute());
			if (answer == null || answer.equals(null)) {
				System.out.println("answer is null");
			} else {
				System.out.println("answer not null");
			}
			if (StringUtils.isEmpty(companyName)) {
				return answer;
			}
			String temp = "OU=" + companyName;
			boolean flag = false; // 标记组织是否存在
			while (answer.hasMoreElements()) {
				SearchResult sr = (SearchResult) answer.next();
				String name = sr.getName();
				if (name.equals(temp)) {
					// 组织单位存在就返回组织单位下的全部信息
					flag = true;
					break;
				}
			}
			if (flag)
				answer = ctx.search("OU=" + companyName + "," + searchbase, "objectClass=*", setAttribute());
			else
				answer = null;
			return answer;
		} catch (NamingException e) {
			Log.error("LadpUtils getADInfoAll error:", e);
			Log.error("LadpUtils getADInfoAll error: 查询失败：" + e.getMessage());
		}
		return null;
	}

	/**
	 * 組人員初始化
	 * 
	 * @param companyName
	 * @return
	 */
	public boolean builders(List<Map<String, Object>> vl, String companyName) {
		try {
			ctx = init();
			NamingEnumeration answer = ctx.search("OU=" + companyName + "," + searchbase, "objectClass=user",
					setAttribute());
			if (answer == null || answer.equals(null)) {
				System.out.println("answer is null");
			} else {
				System.out.println("answer not null");
			}
			Map<String, String> mpath = new HashMap<>();
			if (answer != null) {
				while (answer.hasMoreElements()) {
					SearchResult sr = (SearchResult) answer.next();
					Attributes Attrs = sr.getAttributes();
					if (Attrs != null) {
						String path = sr.getNameInNamespace(); // 部门条目
						String sAMAccountName = Attrs.get("sAMAccountName") == null ? null
								: Attrs.get("sAMAccountName").get().toString();
						if (sAMAccountName != null) {
							mpath.put(sAMAccountName.toLowerCase(), path);
						}
					}
				}
			}
			int sumphone = 0;
			int sumcountry = 0;
			for (Map<String, Object> map : vl) {
				String phone = MapUtils.getString(map, "phone");
				String country = MapUtils.getString(map, "country");
				String login = MapUtils.getString(map, "login_name");
				String path = MapUtils.getString(mpath, login.toLowerCase());
				ModificationItem[] mods = new ModificationItem[1];
				if (phone != null || phone != "") {
					Attribute mobile = new BasicAttribute("mobile", phone);
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mobile);
					ctx.modifyAttributes(path, mods);
					sumphone++;
				}
				if (country != null || country != "") {
					Attribute str = new BasicAttribute("c", country.replaceAll(" ", ""));
					mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, str);
					ctx.modifyAttributes(path, mods);
					sumcountry++;
				}
			}
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.error("LadpUtils builders error:", e);
			Log.error("LadpUtils builders error: 查询失败：" + e.getMessage());
		}

		return true;
	}

	/**
	 * 验证通讯组成员列表是否存在
	 * 
	 * @param memberPath
	 * @return
	 * @throws Exception
	 */
	private boolean isGroubMember(String memberPath) throws Exception {
		memberPath = memberPath.toLowerCase();
		String[] str = memberPath.split(",");
		String parentName = str[2].substring(str[2].indexOf("=") + 1, str[2].length());
		String path = "cn=" + parentName + ",";
		for (int i = 2; i < str.length; i++) {
			if (i < str.length - 1)
				path += str[i] + ",";
			else
				path += str[i];
		}
		NamingEnumeration answer = ctx.search(path, "objectClass=group", setAttribute());
		String member = null;
		while (answer.hasMoreElements()) {
			SearchResult sr = (SearchResult) answer.next();
			Attributes Attrs = sr.getAttributes();
			if (Attrs != null) {
				member = Attrs.get("member") == null ? null : Attrs.get("member").toString();
			}
		}
		String[] members = member == null ? null : member.split(", ");
		for (int i = 1; i < members.length; i++) {
			if (members[i].toLowerCase().equals(memberPath))
				return true;
		}
		return false;
	}

	/**
	 * 
	 * @param companyName
	 *            ou名称
	 * @param login
	 *            登录名
	 * @param pwd
	 *            密码
	 * @return
	 */
	public boolean updatePwd(String companyName, String login, String pwd) {
		try {
			ctx = init();
			NamingEnumeration answer = ctx.search("OU=" + companyName + "," + searchbase, "objectClass=user",
					setAttribute());
			Map<String, String> map = new HashMap<>();
			if (answer != null) {
				while (answer.hasMoreElements()) {
					SearchResult sr = (SearchResult) answer.next();
					Attributes Attrs = sr.getAttributes();
					if (Attrs != null) {
						String sAMAccountName = Attrs.get("sAMAccountName") == null ? null
								: Attrs.get("sAMAccountName").get().toString();// 登录名也是工号
						if (sAMAccountName != null) {
							map.put(sAMAccountName, sr.getNameInNamespace());
						}
					}
				}
			}
			String path = MapUtils.getString(map, login) == null ? null : MapUtils.getString(map, login);
			if (path != null) {
				// 修改密码
				ModificationItem[] mods = new ModificationItem[1];
				String newQuotedPassword = "\"" + pwd + "\"";
				byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
				mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
						new BasicAttribute("unicodePwd", newUnicodePassword));
				ctx.modifyAttributes(path, mods);
				close();
				return true;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.error("LadpUtils updatePwd error:", e);
			Log.error("LadpUtils updatePwd 密码修改错误:" + e.getMessage());
		}
		return false;
	}

}
